// router/index.js
import routes from './routes';
// 引入vue-router对象
import { createRouter, createWebHistory } from 'vue-router';
import storage from '@/utils/storage';

/**
 * 创建路由
 */
const router = createRouter({
  // hash模式：createWebHashHistory，
  // history模式：createWebHistory
  history: createWebHistory('/'),
  // history:createWebHashHistory(),
  scrollBehavior() {
    return { top: 0 };
  },
  linkExactActiveClass: 'active',
  routes,
});

router.beforeEach((to, from, next) => {
  let { token = '' } = storage.getItem('userInfo') || {};
  if (to.path === '/login') {
    if (token !== '') {
      next('/');
      return;
    }
  } else if (token === '' && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next();
});

router.afterEach((to, from) => { });
/**
 * 输出对象
 */
export default router;
